package pm;

import org.apache.log4j.Logger;
import pm.config.Configuration;
import pm.core.Core;
import pm.devices.DevicesModuleImpl;
import pm.gui.GuiModuleImpl;
import pm.oo.OOModuleImpl;
import pm.oo.OOException;
import pm.utils.ClassPathHacker;

import java.io.IOException;
import pm.oo.util.OfficeConnection;

/**
 * Created by fat3kb
 * Date: 03.02.2008
 * Time: 23:24:11
 */
public class PM extends Core {

	private final static Logger logger = Logger.getLogger(PM.class);
	private final static Logger audit = Logger.getLogger("audit");

	private static final String DEFAULT_CFG_PATH = "config\\\\pm.xml";
	public static boolean DEBUG = false;

	/**
	 * Makes initialization and configures modules
	 * according <code>Configuration</code> object and starts
	 * application.
	 *
	 * @param configuration configuration parsed from xml
	 */
	public void launch(final Configuration configuration) throws OOException {
		logger.debug("PM initialization");
		this.configuration = configuration;
		logger.debug(this.configuration.toString());

		PM.DEBUG = this.configuration.getDebug() != null && this.configuration.getDebug();
		logger.debug("Debug mode " + (PM.DEBUG ? "enabled" : "disabled"));

		try {
			ClassPathHacker.addFile(this.configuration.getOoHome() + "\\URE\\java\\juh.jar");
			ClassPathHacker.addFile(this.configuration.getOoHome() + "\\URE\\java\\jurt.jar");
			ClassPathHacker.addFile(this.configuration.getOoHome() + "\\URE\\java\\ridl.jar");
			ClassPathHacker.addFile(this.configuration.getOoHome() + "\\Basis\\program\\classes\\unoil.jar");
		} catch (IOException e) {
			logger.error("Adding of OpenOffice libraries to PM classpath failed", e);
		}

		this.guiModule = new GuiModuleImpl(this, this.configuration);
		this.guiModule.showSplashScreen();

		// Configure devices update thread
		this.devicesModule = new DevicesModuleImpl(this, this.configuration);
		this.guiModule.setDrives(this.devicesModule.getDrives());

		final Long hwnd = this.guiModule.getHWND();
		this.ooModule = new OOModuleImpl(hwnd, configuration.getOoHome() + "\\program");

		this.guiModule.showMainScreen();
		logger.debug("Initialization complete. Show main screen");
		logger.info("PM started");
		audit.info("Application start");
	}

	public static void main(String[] args) {
		logger.debug("PM start");
		try {
			final PM pm = new PM();
			String cfgPath = args.length > 0 ? args[0] : DEFAULT_CFG_PATH;
			logger.debug("Config path : " + cfgPath);
			pm.launch(Configuration.load(cfgPath));
		} catch (Exception e) {
            OfficeConnection.disconnect();
			logger.error("PM start failed", e);
		}
	}
}
